package com.lovo.cloud.service.impl;

import com.lovo.cloud.feginservice.OrderService;
import com.lovo.cloud.model.dos.MovieDO;
import com.lovo.cloud.dao.MovieDAO;
import com.lovo.cloud.model.dos.OrderDO;
import com.lovo.cloud.model.dto.OrderDTO;
import com.lovo.cloud.service.MovieService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author luo
 * @since 2020-12-04
 */
@Service
public class MovieServiceImpl extends ServiceImpl<MovieDAO, MovieDO> implements MovieService {
    @Resource
    private OrderService orderService;

    @Resource
    private MovieDAO movieDAO;

    @RabbitListener(queues = "order")
    @Override
    public boolean updateMovie(OrderDTO orderDTO, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        boolean bl = false;
        try {
            String name = orderDTO.getMovieName();
            MovieDO movieDO = movieDAO.findByName(name);
            if (movieDO != null) {
                if (movieDO.getMovieNumber() < orderDTO.getMovieNum()) {
                    movieDAO.updateMovie(orderDTO);
                    bl = true;
                    orderService.updateOrder(orderDTO.getOrderNum(),true);
                    channel.basicAck(tag,false);
                }else {
                    orderService.updateOrder(orderDTO.getOrderNum(),false);
                    channel.basicAck(tag,false);
                }
            }
        } catch (IOException e) {
            try {
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return bl;
    }
}
